package com.partsoft.spring.webapp;

import java.lang.reflect.Constructor;

import org.springframework.context.ApplicationEvent;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.partsoft.spring.log.Log;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener, ServletRequestListener {

	private ServletRequestListener servletRequestListener = new RequestContextListener();
	
	
	public void sessionCreated(HttpSessionEvent se) {
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(se.getSession().getServletContext());
		
		Class<?> evClazz = null;
		try {
			try {
				evClazz = ClassUtils.forName("org.springframework.security.ui.session.HttpSessionCreatedEvent", ClassUtils.getDefaultClassLoader());
			} catch (Throwable ea) {}
			if (evClazz != null) {
				Constructor<?> evConstructor =  ClassUtils.getConstructorIfAvailable(evClazz, HttpSession.class);
				if (evConstructor != null) {
					ApplicationEvent appEvent = (ApplicationEvent) evConstructor.newInstance(se.getSession());
					wac.publishEvent(appEvent);
				}
			}
		}  catch (Throwable e) {
			Log.error("Occur an error when HttpSessionCreatedEvent creating:", e);
		}

	}

	public void sessionDestroyed(HttpSessionEvent se) {
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(se.getSession().getServletContext());
		
		Class<?> evClazz = null;
		try {
			try {
				evClazz = ClassUtils.forName("org.springframework.security.ui.session.HttpSessionDestroyedEvent", ClassUtils.getDefaultClassLoader());
			} catch (Throwable ea) {}
			if (evClazz != null) {
				Constructor<?> evConstructor =  ClassUtils.getConstructorIfAvailable(evClazz, HttpSession.class);
				if (evConstructor != null) {
					ApplicationEvent appEvent = (ApplicationEvent) evConstructor.newInstance(se.getSession());
					wac.publishEvent(appEvent);
				}
			}
		}  catch (Throwable e) {
			Log.error("Occur an error when HttpSessionDestroyedEvent destroying:", e);
		}
	}

	public void requestDestroyed(ServletRequestEvent sre) {
		servletRequestListener.requestDestroyed(sre);
	}

	public void requestInitialized(ServletRequestEvent sre) {
		servletRequestListener.requestInitialized(sre);
	}

}
